package com.cmc.cloud.cmclink.doc.service.impl.si;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cmc.cloud.cmclink.csm.api.base.dto.req.CompanyNameCastReqVO;
import com.cmc.cloud.cmclink.csm.api.base.dto.resp.CompanyNameCastRespDTO;
import com.cmc.cloud.cmclink.doc.api.document.emums.SiValidEnum;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.BlnoErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.BlnoScnErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.convert.BlnoScnConvert;
import com.cmc.cloud.cmclink.doc.entity.BlnoDO;
import com.cmc.cloud.cmclink.doc.entity.BlnoScnDO;
import com.cmc.cloud.cmclink.doc.mapper.BlnoMapper;
import com.cmc.cloud.cmclink.doc.mapper.BlnoScnMapper;
import com.cmc.cloud.cmclink.doc.rpcservice.CustomerRpcService;
import com.cmc.cloud.cmclink.doc.service.si.BlnoScnService;
import com.cmc.cloud.cmclink.doc.vo.blnoscnvo.BlnoScnCreateReqVO;
import com.cmc.cloud.cmclink.doc.vo.blnoscnvo.BlnoScnPageReqVO;
import com.cmc.cloud.cmclink.doc.vo.blnoscnvo.BlnoScnUpdateReqVO;
import com.cmc.cloud.cmclink.doc.vo.blnoscnvo.LinkCpfCodeReqVO;
import com.cmes.framework.common.exception.util.ServiceExceptionUtil;
import com.cmes.framework.common.pojo.PageResult;
import com.cmes.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 提单收发通信息 Service 实现类
 *
 * @author 集运管理员
 */
@Service
@Validated
public class BlnoScnServiceImpl implements BlnoScnService {

    @Resource
    private BlnoScnMapper blnoScnMapper;

    @Resource
    private BlnoMapper blnoMapper;

    @Resource
    private CustomerRpcService nameTransferService;

    @Override
    public void createBlnoScn(BlnoScnCreateReqVO createReqVO) {
        // 插入
        BlnoScnDO blnoScn = BlnoScnConvert.INSTANCE.convert(createReqVO);
        blnoScnMapper.insert(blnoScn);
    }

    @Override
    public void updateBlnoScn(BlnoScnUpdateReqVO updateReqVO) {
        // 校验存在
        validateBlnoScnExists(updateReqVO.getId());
        // 更新
        BlnoScnDO updateObj = BlnoScnConvert.INSTANCE.convert(updateReqVO);
        blnoScnMapper.updateById(updateObj);
    }

    @Override
    public void deleteBlnoScn(Long id) {
        // 校验存在
        validateBlnoScnExists(id);
        // 删除
        blnoScnMapper.deleteById(id);
    }
    @Override
    public void deleteBlnoScnByblnoId(Long blnoId) {
        LambdaQueryWrapper<BlnoScnDO> scnQueryWrapper = new LambdaQueryWrapper<>();
        scnQueryWrapper.eq(BlnoScnDO::getBlnoId, blnoId);
        blnoScnMapper.delete(scnQueryWrapper);
    }

    @Override
    public List<BlnoScnDO> getScnByBlNo(String blNo) {
        LambdaQueryWrapper<BlnoDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlnoDO::getBlNo, blNo).eq(BlnoDO::getValid, SiValidEnum.VALID.getValue());
        BlnoDO blnoDO = blnoMapper.selectOne(queryWrapper);
        if (blnoDO == null) {
            throw ServiceExceptionUtil.exception(BlnoErrorCodeConstants.BLNO_NOT_EXISTS);
        }
        LambdaQueryWrapper<BlnoScnDO> scnQueryWrapper = new LambdaQueryWrapper<>();
        scnQueryWrapper.eq(BlnoScnDO::getBlnoId, blnoDO.getId());
        scnQueryWrapper.orderByAsc(BlnoScnDO::getId);
        return blnoScnMapper.selectList(scnQueryWrapper);
    }

    private void validateBlnoScnExists(Long id) {
        if (blnoScnMapper.selectById(id) == null) {
            throw ServiceExceptionUtil.exception(BlnoScnErrorCodeConstants.BLNO_SCN_NOT_EXISTS);
        }
    }

    @Override
    public BlnoScnDO getBlnoScn(Long id) {
        return blnoScnMapper.selectById(id);
    }

    @Override
    public List<BlnoScnDO> getBlnoScnByBlnoId(Long blnoId) {
        LambdaQueryWrapper<BlnoScnDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlnoScnDO::getBlnoId, blnoId);
        queryWrapper.orderByAsc(BlnoScnDO::getId);
        return blnoScnMapper.selectList(queryWrapper);
    }

    @Override
    public List<BlnoScnDO> getBlnoScnByBlnoIdList(Collection<Long> ids) {
        LambdaQueryWrapperX<BlnoScnDO> queryWrapperX = new LambdaQueryWrapperX<>();
        queryWrapperX.in(BlnoScnDO::getBlnoId, ids);
        return blnoScnMapper.selectList(queryWrapperX);
    }

    @Override
    public List<BlnoScnDO> getBlnoScnList(Collection<Long> ids) {
        return blnoScnMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<BlnoScnDO> getBlnoScnPage(BlnoScnPageReqVO reqVO) {
        IPage<BlnoScnDO> page = Page.of(reqVO.getPageNo(), reqVO.getPageSize());
        IPage<BlnoScnDO> result = blnoScnMapper.selectPageList(page, reqVO);
        return new PageResult<BlnoScnDO>(result.getRecords(), result.getTotal());
    }

    @Override
    public void createOrUpdateAndDeleteBatch(Long blnoId, List<BlnoScnUpdateReqVO> newList, List<BlnoScnUpdateReqVO> oldList) {
        // 无效数据直接返回
        if (CollectionUtil.isEmpty(newList) && CollectionUtil.isEmpty(oldList)) {
            return;
        }
        // 默认值
        if (CollectionUtil.isEmpty(newList)) {
            newList = new ArrayList<>();
        }
        if (CollectionUtil.isEmpty(oldList)) {
            oldList = new ArrayList<>();
        }
        List<BlnoScnUpdateReqVO> createList = new ArrayList<>();
        List<BlnoScnUpdateReqVO> updateList = new ArrayList<>();
        // 历史数据
        Set<Long> oldIds = oldList.stream().map(e -> e.getId()).collect(Collectors.toSet());
        newList.forEach(e -> {
            if (e.getId() != null) {
                if (oldIds.contains(e.getId())) {
                    // 正常更新
                    updateList.add(e);
                    oldIds.remove(e.getId()); // 剩下的数据需要删除
                } else {
                    // 数据更新非法
                    throw ServiceExceptionUtil.exception(BlnoErrorCodeConstants.SI_NI_UPDATE);
                }
            } else {
                e.setBlnoId(blnoId);
                createList.add(e);
            }
        });
        if (CollectionUtil.isNotEmpty(oldIds)) {
            // 没有匹配上的就是前端删除的
            blnoScnMapper.deleteBatchIds(oldIds);
        }
        if (CollectionUtil.isNotEmpty(createList)) {
            List<BlnoScnDO> scnCreateList = BeanUtil.copyToList(createList, BlnoScnDO.class);
            blnoScnMapper.insertBatch(scnCreateList);
        }
        if (CollectionUtil.isNotEmpty(updateList)) {
            List<BlnoScnDO> scnUpdateList = BeanUtil.copyToList(updateList, BlnoScnDO.class);
            blnoScnMapper.updateBatch(scnUpdateList);
        }
    }

    @Override
    public String bindCpfCode(LinkCpfCodeReqVO linkCpfCodeReqVO) {
        CompanyNameCastReqVO companyNameCastReqVO = new CompanyNameCastReqVO();
        companyNameCastReqVO.setCsmCodeList(Arrays.asList(linkCpfCodeReqVO.getCsmCode()));
        List<CompanyNameCastRespDTO> companyNameCastRespDtos = nameTransferService.customerFromCodeList(companyNameCastReqVO);
        if (CollectionUtil.isEmpty(companyNameCastRespDtos)) {
            throw ServiceExceptionUtil.exception(BlnoErrorCodeConstants.SI_SCN_CPF_NOT_EXISTED);
        }
        blnoScnMapper.update(null,new LambdaUpdateWrapper<BlnoScnDO>()
                .eq(BlnoScnDO::getBlnoId,linkCpfCodeReqVO.getBlnoId())
                .eq(BlnoScnDO::getPartyTypeCode,linkCpfCodeReqVO.getPartyTypeCode())
                .set(BlnoScnDO::getCsmCode,linkCpfCodeReqVO.getCsmCode())
                .set(BlnoScnDO::getUpdateTime, LocalDateTime.now()));
        CompanyNameCastRespDTO companyNameCastRespDTO = companyNameCastRespDtos.get(0);
        return companyNameCastRespDTO.getCompanyNameLocal();
    }
}
